<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\translation\providers;

/**
 * OpenAI翻译提供商
 */
class OpenAITranslateProvider extends AbstractTranslateProvider
{
    protected function validateConfig()
    {
        if (!$this->hasConfig('api_key')) {
            throw new \Exception('OpenAI翻译需要配置 api_key');
        }
    }

    public function translate($text, $targetLanguage, $sourceLanguage = 'zh_CN')
    {
        $text = $this->cleanText($text);
        if (empty($text)) {
            return '';
        }

        $targetLangName = $this->getLanguageName($targetLanguage);
        $sourceLangName = $this->getLanguageName($sourceLanguage);

        $prompt = "请将以下{$sourceLangName}文本翻译成{$targetLangName}，保持原文的格式和语气，只返回翻译结果：\n\n{$text}";

        $data = [
            'model'       => $this->getConfig('model', 'gpt-3.5-turbo'),
            'messages'    => [
                [
                    'role'    => 'user',
                    'content' => $prompt
                ]
            ],
            'temperature' => $this->getConfig('temperature', 0.3),
            'max_tokens'  => min(4000, strlen($text) * 2),
        ];

        $headers = [
            'Authorization: Bearer ' . $this->getConfig('api_key'),
            'Content-Type: application/json',
        ];

        try {
            $response = $this->sendRequest($this->getConfig('endpoint'), $data, 'POST', $headers);
            $result   = json_decode($response, true);

            if (!$result || isset($result['error'])) {
                $errorMsg = $result['error']['message'] ?? '翻译请求失败';
                throw new \Exception($errorMsg);
            }

            if (!isset($result['choices'][0]['message']['content'])) {
                throw new \Exception('翻译结果格式错误');
            }

            $translatedText = trim($result['choices'][0]['message']['content']);
            $this->logTranslation($text, $translatedText, $targetLanguage, $sourceLanguage, 'openai');

            return $translatedText;

        } catch (\Exception $e) {
            $this->handleTranslationError($e->getMessage(), 'openai');
        }
    }

    private function getLanguageName($languageCode)
    {
        $languageNames = [
            'zh_CN' => '中文',
            'en_US' => '英文',
            'ja_JP' => '日文',
            'ko_KR' => '韩文',
            'fr_FR' => '法文',
            'de_DE' => '德文',
            'es_ES' => '西班牙文',
            'pt_PT' => '葡萄牙文',
            'ru_RU' => '俄文',
            'ar_SA' => '阿拉伯文',
        ];

        return $languageNames[$languageCode] ?? '英文';
    }
}
